import requests
from django.http import JsonResponse
from rest_framework.views import APIView
from database import models
import os
import time

from utils.requests_pro import find_province

BASE_DIR = os.path.dirname(os.path.abspath(__file__))



class RequestsMain(APIView):

    def post(self, request):

        city_code = request.data.get("city_code")
        start_page = int(request.data.get("start_page"))
        stop_page = int( request.data.get("stop_page"))

        message = {}
        try:
            session = requests.Session()
            cookies =str( models.Cookies.objects.last().cookies).replace(" ","")

            headers = {
                "cookie": cookies,
                "referer": "https://www.zhipin.com/web/job?query=&city=100010000&page=1",
                "user-agent": "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
            }
            for _ in range(start_page, stop_page + 1):

                page = session.get(
                    url="https://www.zhipin.com/wapi/search/joblist.json?scene=1&query=&city={}&experience=&degree=&industry=&scale=&stage=&position=&jobType=&salary=&multiBusinessDistrict=&multiSubway=&page={}&pageSize=30".format(
                        city_code, _), headers=headers)

                json_data = eval(page.text.replace("true", "1").replace("false", "2").replace("null", "0"))
                for obj in json_data.get('zpData').get('jobList'):
                    try:
                        brandLogo = obj.get('brandLogo')  # 公司LOGO
                        brandName = obj.get('brandName')  # 公司名称
                        url = "https://www.zhipin.com/job_detail/{}.html".format(obj.get('encryptJobId'))  # 详情
                        # 工资
                        salaryDesc_raw = obj.get('salaryDesc')  # 工资
                        wages = float(str(salaryDesc_raw).split("-")[0].replace("千", ""))
                        if 1 <= wages < 3:
                            salaryDesc = wages * 10000
                        if 3 <= wages <= 9:
                            salaryDesc = wages * 1000
                        if wages > 10:
                            salaryDesc = int(str(int((wages * 10000) / 12))[0:2] + "000")
                        if salaryDesc > 20000:
                            salaryDesc = float(str(salaryDesc / 5)[0:2] + "00")

                        bossName = obj.get('bossName')  # 招聘人
                        bossTitle = obj.get('bossTitle')  # 招聘人职位
                        jobName = obj.get('jobName')  # 招聘职位
                        jobExperience = obj.get('jobExperience')  # 需求经验
                        jobDegree = obj.get('jobDegree')  # 学历
                        skills = ",".join(obj.get('skills'))  # 掌握技能
                        cityName = obj.get('cityName')  # 城市
                        province = find_province(cityName)  # 省份
                        areaDistrict = obj.get('areDistrict')  # 区域
                        brandStageName = obj.get('brndStageName')  # 融资情况
                        brandIndustry = obj.get('brandIndustry')  # 公司分类
                        brandScaleName = obj.get('brandScaleName')  # 公司规模
                        welfareList = ",".join(obj.get('welfareList'))  # 福利
                        print("岗位：{} 正在入库".format(jobName))
                        if models.Total.objects.filter(jobName=jobName).exists() == False:
                            models.Total.objects.create(brandLogo=brandLogo, brandName=brandName, url=url, wages=salaryDesc,
                                                        bossName=bossName, bossTitle=bossTitle, skills=skills,
                                                        jobName=jobName, jobExperience=jobExperience, jobDegree=jobDegree,
                                                        cityName=cityName, province=province, areaDistrict=areaDistrict,
                                                        brandStageName=brandStageName, brandIndustry=brandIndustry,
                                                        brandScaleName=brandScaleName, welfareList=welfareList)
                    except:
                        pass

            message['code'] = 200
            message['message'] = "OK"
            return JsonResponse(message)
        except Exception as e:
            print(e)
            message['code'] = 444
            message['message'] = "爬取异常，请联系管理员Q  995405033 进行处理"
            return JsonResponse(message)
